import { expect } from '@jest/globals';
import * as compressing from 'compressing';
import fsExtra from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.EmptyAbility]: 1
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp'
  });
  const result = await runHvigorAsync(projectRootPath, command);
  record.addStep('执行 Build App', result);
  expect(result.stdout).toContain('Finished :entry:assembleHap');
  expect(result.stdout).toContain('Finished :application:assembleHap');
  expect(result.stdout).toContain('Finished ::PackageApp');
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 解析app包的内容
  await fsExtra.copyFile(path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned.app'),
    path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned.zip'));
  await compressing.zip.uncompress(
    path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned.zip'),
    path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned'));

  // 查看app包里是否有多个hap包
  const applicationHapExist = await fsExtra.pathExists(
    // eslint-disable-next-line max-len
    path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned/application-entry-default.hap'));
  const entryHapExist = await fsExtra.pathExists(
    path.resolve(projectRootPath, 'build/outputs/default/myapplication-default-unsigned/entry-default.hap'));
  expect(applicationHapExist).toBe(true);
  expect(entryHapExist).toBe(true);

};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_module_build_multiHap_HOS_api10_STAGE_006')
  .description('Stage模型，hos_eTS多模块工程打APP包_entry和feature')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
